<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>FastAPI流式数据演示</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            max-width: 900px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f7fa;
            color: #333;
        }
        h1 {
            color: #2c3e50;
            text-align: center;
            margin-bottom: 30px;
        }
        .container {
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            padding: 25px;
            margin-bottom: 20px;
        }
        .button-container {
            display: flex;
            gap: 15px;
            justify-content: center;
            margin-bottom: 20px;
        }
        button {
            padding: 12px 24px;
            border: none;
            border-radius: 6px;
            background-color: #3498db;
            color: white;
            font-weight: bold;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        button:hover {
            background-color: #2980b9;
        }
        button:disabled {
            background-color: #95a5a6;
            cursor: not-allowed;
        }
        #stopButton {
            background-color: #e74c3c;
        }
        #stopButton:hover {
            background-color: #c0392b;
        }
        .status {
            text-align: center;
            margin: 15px 0;
            padding: 10px;
            border-radius: 5px;
            font-weight: bold;
        }
        .connected {
            background-color: #d4edda;
            color: #155724;
        }
        .disconnected {
            background-color: #f8d7da;
            color: #721c24;
        }
        .data-container {
            max-height: 400px;
            overflow-y: auto;
            border: 1px solid #ddd;
            border-radius: 5px;
            padding: 15px;
            background-color: #f9f9f9;
        }
        .message {
            padding: 10px;
            margin-bottom: 10px;
            border-left: 4px solid #3498db;
            background-color: #edf2f7;
            border-radius: 0 4px 4px 0;
        }
        .message .timestamp {
            font-size: 0.8em;
            color: #7f8c8d;
            margin-bottom: 5px;
        }
        .message .content {
            word-break: break-word;
        }
        .instructions {
            background-color: #fff3cd;
            border-left: 4px solid #ffc107;
            padding: 15px;
            margin-top: 20px;
            border-radius: 0 4px 4px 0;
        }
    </style>
</head>
<body>
    <h1>FastAPI流式数据演示</h1>

    <div class="container">
        <div class="button-container">
            <button id="connectButton">连接流式数据</button>
            <button id="stopButton" disabled>停止连接</button>
        </div>

        <div id="status" class="status disconnected">未连接</div>

        <h3>接收到的数据:</h3>
        <div id="dataContainer" class="data-container">
            <div class="message">
                <div class="timestamp">等待数据中...</div>
                <div class="content">连接后将在此处显示实时数据</div>
            </div>
        </div>
    </div>

    <div class="container instructions">
        <h3>使用说明:</h3>
        <ol>
            <li>确保FastAPI后端服务器正在运行 (端口8000)</li>
            <li>点击"连接流式数据"按钮开始接收数据</li>
            <li>使用另一个Python脚本向后端发送数据</li>
            <li>数据将实时显示在上方区域</li>
            <li>点击"停止连接"按钮可以中断连接</li>
        </ol>
    </div>

    <script>
        // 全局变量
        let eventSource = null;
        let clientId = null;
        const connectButton = document.getElementById('connectButton');
        const stopButton = document.getElementById('stopButton');
        const statusDiv = document.getElementById('status');
        const dataContainer = document.getElementById('dataContainer');

        // 更新状态显示
        function updateStatus(connected) {
            if (connected) {
                statusDiv.textContent = `已连接 (客户端ID: ${clientId})`;
                statusDiv.className = 'status connected';
                connectButton.disabled = true;
                stopButton.disabled = false;
            } else {
                statusDiv.textContent = '未连接';
                statusDiv.className = 'status disconnected';
                connectButton.disabled = false;
                stopButton.disabled = true;
            }
        }

        // 添加消息到显示区域
        function addMessage(data) {
            // 清除等待消息
            if (dataContainer.innerHTML.includes('等待数据中...')) {
                dataContainer.innerHTML = '';
            }

            const messageDiv = document.createElement('div');
            messageDiv.className = 'message';

            const timestamp = new Date().toLocaleTimeString();
            const content = typeof data === 'object' ? JSON.stringify(data, null, 2) : data;

            messageDiv.innerHTML = `
                <div class="timestamp">${timestamp}</div>
                <div class="content">${content}</div>
            `;

            dataContainer.prepend(messageDiv);

            // 自动滚动到最新消息
            dataContainer.scrollTop = 0;
        }

        // 连接到流式端点
        async function connectToStream() {
            try {
                // 首先获取客户端ID
                const response = await fetch('http://localhost:8000/stream', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                });

                if (!response.ok) {
                    throw new Error('无法连接到服务器');
                }

                // 使用EventSource API接收服务器发送的事件
                eventSource = new EventSource('http://localhost:8000/stream');

                eventSource.onmessage = function(event) {
                    try {
                        const data = JSON.parse(event.data);
                        addMessage(data);
                    } catch (e) {
                        console.error('解析数据错误:', e);
                        addMessage(`原始数据: ${event.data}`);
                    }
                };

                eventSource.onerror = function(error) {
                    console.error('EventSource错误:', error);
                    disconnectFromStream();
                    alert('连接发生错误，请检查服务器状态');
                };

                // 模拟获取客户端ID（实际中需要后端支持）
                clientId = 'demo-client-' + Math.random().toString(36).substr(2, 9);
                updateStatus(true);

                addMessage({
                    type: 'system',
                    message: '连接已建立',
                    clientId: clientId
                });

            } catch (error) {
                console.error('连接错误:', error);
                alert('连接失败: ' + error.message);
            }
        }

        // 断开连接
        function disconnectFromStream() {
            if (eventSource) {
                eventSource.close();
                eventSource = null;
            }

            clientId = null;
            updateStatus(false);

            addMessage({
                type: 'system',
                message: '连接已断开'
            });
        }

        // 添加事件监听器
        connectButton.addEventListener('click', connectToStream);
        stopButton.addEventListener('click', disconnectFromStream);

        // 初始化状态
        updateStatus(false);
    </script>
</body>
</html>